package com.hopu.dxhouse.mapper;

import com.hopu.dxhouse.entity.MyEmp;

import java.sql.*;

/**
 * @Package: com.hopu.dxhouse.mapper
 * @ClassName: MyEmpDaoImple
 * @Author: Administrator
 * @CreateTime: 2020/10/19 16:57
 * @Description:
 */
public class MyEmpDaoImple implements MyEmpDao{

    /**
     * 用jdbc操作数据库步骤
     * 1、注册驱动
     * 2、获取连接
     * 3、预处理语句
     * 4、执行SQL语句获取数据
     */

    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/dxhouse?serverTimezone=UTC&characterEncoding=UTF-8";
    private String username = "root";
    private String password = "123456";

    private Connection connection;  //获取数据库连接
    private PreparedStatement ps;   //预处理对象
    private ResultSet resultSet;        //返回结果集

    /**
     * 初始化连接，在类加载时
     */
    public void init(){
        /**
         * 初始化连接
         * 1、注册驱动
         * 2、获取连接
         */

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }


    @Override   //通过JDBC连接数据库验证用户名是否正确
    public MyEmp checkEname(String ename) {
        init();
        String sqlStr = "SELECT * FROM myemp WHERE ename = '"+ename+"'";
        try {

            //预处理SQL语句
            ps = connection.prepareStatement(sqlStr);
            //执行SQL语句获取返回的结果集
            resultSet = ps.executeQuery();
            //实例化MyEmp对象用于遍历SQL语句执行返回的集合
            MyEmp emp = new MyEmp();
            //遍历结果集
            while (resultSet.next()){
                //获取结果集的内容将值设置进实体类
                emp.setEname(resultSet.getString("ename"));
            }
            return emp;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override   //通过JDBC连接数据库验证账号和密码是否正确
    public MyEmp checkEnameAndEpsw(String ename, String epsw) {
        init();
        String sqlStr = "SELECT * FROM myemp WHERE ename = '"+ename+"' AND epsw = '"+epsw+"'";
        try {

            //预处理SQL语句
            ps = connection.prepareStatement(sqlStr);
            //执行SQL语句获取返回的结果集
            resultSet = ps.executeQuery();
            //实例化MyEmp对象用于遍历SQL语句执行返回的集合
            MyEmp emp = new MyEmp();
            //遍历结果集
            while (resultSet.next()){
                //获取结果集的内容将值设置进实体类
                emp.setEname(resultSet.getString("ename"));
                emp.setEpsw(resultSet.getString("epsw"));
            }
            return emp;

        } catch (SQLException throwables) {
           throwables.printStackTrace();
        }
        return null;
    }
}
